package com.bootdo.clouddoexam.controller;


import com.bootdo.clouddocommon.context.FilterContextHandler;
import com.bootdo.clouddocommon.utils.FileUtils;
import com.bootdo.clouddoexam.domain.ScoreDO;
import com.bootdo.clouddocommon.utils.PageUtils;
import com.bootdo.clouddocommon.utils.Query;
import com.bootdo.clouddocommon.utils.R;
import com.bootdo.clouddoexam.service.ScoreService;
import com.bootdo.clouddoexam.util.POIUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * 文件上传
 *
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2018-03-12 12:17:36
 */

@RestController
@RequestMapping("/exam")
public class ExamController {
    @Value("${app.filePath}")
    String filePath;

    @Autowired
    private ScoreService scoreService;

    @GetMapping("{id}")
    public R get(@PathVariable String id) {
        ScoreDO blog = scoreService.get(id);
        return R.data(blog);
    }
    @GetMapping("examonline")
    public R examonline(@RequestParam Map<String, Object> params) {
      System.out.println(">>>>>>>>>>.id"+params.get("choose_answer"));
        System.out.println(">>>>>>>>>>.id"+params.get("short_answer"));
        if(params.get("choose_answer").equals("")&&params.get("short_answer").equals("")){
            return R.error();
        }else{
            return R.ok();
        }

    }


    /**
     * 分页查询
     */
    @GetMapping
    public R list(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        List<ScoreDO> fileList = scoreService.list(query);
//        List<FileDTO> fileDTOS = FileConvert.MAPPER.dos2dtos(fileList);
        System.out.println("wo>>>>>>>>>>"+fileList);
        System.out.println("wo2222>>>>>>>>>>"+params);
        int total = scoreService.count(query);
//        PageUtils pageUtils = new PageUtils(fileDTOS, total);
        PageUtils pageUtils = new PageUtils(fileList, total);
        return R.page(pageUtils);
    }
    @GetMapping("getToken")
    public R getToken() {
        return R.ok().put("token", FilterContextHandler.getToken()).put("url", "http://localhost:8002/api-exam/exam/upload")
                .put("key", UUID.randomUUID().toString());
    }
    @GetMapping("getTokenscore")
    public R getTokenscore(String id) {
        System.out.println(">>>>>>"+id);
        return R.ok().put("token", FilterContextHandler.getToken()).put("url", "http://localhost:8002/api-exam/exam/uploadscore")
                .put("key", id);
    }
    @PostMapping("upload")
    public R upload(MultipartFile file, String key) throws IOException {
        System.out.println(">>>>>>"+key);
        try {
            List<String[]>  result = POIUtil.readExcel(file);
            ScoreDO score=new ScoreDO();
            for(int i=1;i<result.size();i++){
                score.setStudentId(result.get(i)[0]);
                score.setStudentName(result.get(i)[1]);
                score.setStydentGrade(result.get(i)[2]);
                scoreService.save(score);
            }
            return R.ok().put("resPath", "导入成功");
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("文件导入失败");
        }
    }
    @PostMapping("uploadscore")
    public R uploadscore(MultipartFile file, String key) throws IOException {
        System.out.println(">>>>>>>>>"+key);
        try {
            List<String[]>  result = POIUtil.readExcel(file);
            ScoreDO score=new ScoreDO();
            for(int i=1;i<result.size();i++){
                score.setStudentId(result.get(i)[0]);
                int ch = Integer.parseInt(key);
                switch (ch) {
                    case 0:
                        score.setGeography(Integer.parseInt(result.get(i)[3]));
                        break;
                    case 1:
                        score.setChemistry(Integer.parseInt(result.get(i)[3]));
                        break;
                    case 2:
                        score.setHistory(Integer.parseInt(result.get(i)[3]));
                        break;
                    case 3:
                        score.setBiology(Integer.parseInt(result.get(i)[3]));
                        break;
                    case 4:
                        score.setMathematics(Integer.parseInt(result.get(i)[3]));
                        break;
                    case 5:
                        score.setPhysical(Integer.parseInt(result.get(i)[3]));
                        break;
                    case 6:
                        score.setEnglish(Double.parseDouble(result.get(i)[3]));
                        break;
                    case 7:
                        score.setChinese(Double.parseDouble(result.get(i)[3]));
                        break;
                    case 8:
                        score.setGovernment(Integer.parseInt(result.get(i)[3]));
                        break;
                    default:

                        break;
                }
                scoreService.update(score);
            }
            return R.ok().put("resPath", "导入成功");
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("文件导入失败");
        }
    }
    @GetMapping("getTokenout")
    public R getTokenout(String id) {
        System.out.println(">>>>>>"+id);
        return R.ok().put("token", FilterContextHandler.getToken()).put("url", "http://localhost:8002/api-exam/exam/export")
                .put("key", id);
    }
    @PostMapping ( "/export")
    public void exportExecl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("aaaaaaaaaaaaaaaaa");
        List<ScoreDO> list = scoreService.listall("二", "02","Chinese");
        XSSFWorkbook wb = POIUtil.export(list);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + "test" + ".xlsx");
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();


    }

    /**
     * 保存
     */
    @PostMapping
    public R save(ScoreDO file) {
        return R.operate(scoreService.save(file) > 0);
    }

    /**
     * 修改
     */
    @PutMapping
    public R update(ScoreDO file) {
        return R.operate(scoreService.update(file) > 0);
    }

    /**
     * 删除
     */
    @DeleteMapping
    public R remove(String id) {
        System.out.println("传入的删除id"+id);
        System.out.println("dddddddddddddddddddddd");
        return R.operate(scoreService.remove(id) > 0);
    }

    /**
     * 删除
     */
    @DeleteMapping("/batchRemove")
    public R remove(@RequestParam("ids[]") String[] ids) {
        return R.operate(scoreService.batchRemove(ids) > 0);
    }
}
